package com.example.security.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
  public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
    super(authenticationManager);
  }

  @Override
  // 从request中获取token, 并进行校验, 最后存入SecurityContextHolder中
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    String token = request.getHeader("Authorization");
    if (token == null || !token.startsWith("Bearer")) {
      chain.doFilter(request, response);
      return;
    }
    // 有token
    // 去掉前缀
    token = token.replace("Bearer ", "");
    try {
      var decodedToken = JWT.require(Algorithm.HMAC512("MY-JWT".getBytes())).build().verify(token);
      var username = decodedToken.getSubject();
      if (username != null) {
        // 成功认证
        List<GrantedAuthority> authorities = new ArrayList<>();
        decodedToken.getClaim("roles").asList(String.class).forEach(a -> authorities.add(() -> a));
        SecurityContextHolder.getContext()
            .setAuthentication(
                new UsernamePasswordAuthenticationToken(username, null, authorities));
      }
    } catch (JWTVerificationException e) {
      logger.info("Token非法");
    }
    chain.doFilter(request, response);
  }
}
